﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MindMapper.Business;

namespace MindMapper.Providers.Linq2Sql
{
    public class MindMapLinq2SqlProvider : IMindMapProvider
    {
        public Business.MindMap Get(string id)
        {
            using (var context = new MindMapDataClassesDataContext())
            {
                var map = context.MindMaps.SingleOrDefault(m => m.Id == id);
                if (map == null)
                    return null;
                var nodes = map.MindMapNodes.ToList();

                return new Business.MindMap()
                {
                    Id = id,
                    Nodes = Convert(nodes)
                    //Root = ChildNodes(nodes, null).SingleOrDefault()
                };
            }
        }

        private List<Business.MindMapNode> Convert(List<MindMapNode> nodes)
        {
            var list = new List<Business.MindMapNode>();
            foreach (var item in nodes)
            {
                list.Add(new Business.MindMapNode()
                {
                    Id = item.Id,
                    Text = item.Text,
                    ParentId = item.ParentId
                });
            }

            foreach (var item in list)
            {
                if (string.IsNullOrEmpty(item.ParentId))
                    continue;

                var parent = list.Single(n => n.Id == item.ParentId);
                parent.ChildNodesIds.Add(item.Id);
            }
            return list;
        }

        //private List<Business.MindMapNode> ChildNodes(List<MindMapNode> nodes, Business.MindMapNode parentMindMapNode)
        //{
        //    return nodes.Where(n => (parentMindMapNode == null && n.ParentId == null) || (parentMindMapNode != null && n.ParentId == parentMindMapNode.Id))
        //        .Select(n =>
        //    {
        //        var mindMapNode = new Business.MindMapNode()
        //            {
        //                Id = n.Id,
        //                Text = n.Text,
        //                Parent = parentMindMapNode
        //            };
        //        mindMapNode.ChildNodes = ChildNodes(nodes, mindMapNode);
        //        return mindMapNode;
        //    }).ToList();
        //}
    }
}
